package com.mediacloud.app.newsmodule.fragment.recommend;

import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;

import android.os.Handler;
import android.os.Parcelable;
import android.util.Log;
import android.view.View;

import com.mediacloud.app.appointment.AppointmentManager;
import com.mediacloud.app.assembly.adapter.IAdapterTitle;
import com.mediacloud.app.model.eventbus.event.LoginEvent;
import com.mediacloud.app.model.interfaces.DataInvokeCallBack;
import com.mediacloud.app.model.news.ArticleItem;
import com.mediacloud.app.model.news.LiveProgramListReciver;
import com.mediacloud.app.model.news.LiveProgramListReciver.ProgramWeekItem;
import com.mediacloud.app.model.news.ProgramListItem;
import com.mediacloud.app.newsmodule.activity.VideoLiveDetailActivity;
import com.mediacloud.app.reslib.util.DataInvokeUtil;
import com.mediacloud.app.user.model.UserInfo;
import com.mediacloud.app.newsmodule.R;
import com.mediacloud.app.newsmodule.fragment.newslist.TableCatalogItemsFragmentBase;
import com.mediacloud.app.newsmodule.fragment.video.live.LiveProgramItemFragment;
import com.mediacloud.app.newsmodule.model.SimpleNavigateItem;
import com.mediacloud.app.newsmodule.utils.AppThemeTabLayoutStyle;
import com.mediacloud.app.newsmodule.utils.ComponentRelativeInvoker;
import com.mediacloud.app.newsmodule.utils.AppfacBuyEnableUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.Serializable;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by yoake on 2017/10/9.
 */
public class ComponentLiveListFragment extends TableCatalogItemsFragmentBase<SimpleNavigateItem> implements DataInvokeCallBack<LiveProgramListReciver> {

    public static final String Program = "Program";
    /**
     * 选择的日期索引
     */
    public GetProgramData programGetHandle;
    protected ArrayList<ProgramWeekItem> programListItems;
    public int todayPosition;
    public ArrayList<Map<String, List<ProgramListItem>>> allProgramList = new ArrayList<>();
    public ComponentRelativeInvoker componentRelativeInvoker;
    public String componentId;
    public String article_id;
    public String channelName;
    public String vid;
    private boolean needPay = false;
    private ArticleItem item;

    @Override
    protected void getArgs() {
        navigateItems = new ArrayList<>();
        componentId = getFragmentArguments().getString("componentId");
        article_id = getFragmentArguments().getString("article_id");
        channelName = getFragmentArguments().getString("channelName");
        vid = getFragmentArguments().getString("vid");
        needPay = getFragmentArguments().getBoolean("needPay");
        item = getFragmentArguments().getParcelable("item");
        programListItems = (ArrayList<LiveProgramListReciver.ProgramWeekItem>) getFragmentArguments().getSerializable(Program);
//        if (UserInfo.isLogin(getContext()))//用户登录，请求预约节目单
//            getAppointmentList(article_id);
    }


    @Override
    public void initView() {
        super.initView();
        topContainer.setBackgroundResource(R.drawable.jinghua_listdivider);
        getRelateNewsList();
    }

    /**
     * 获取数据列表
     */
    public void getRelateNewsList() {
        componentRelativeInvoker = new ComponentRelativeInvoker(this);
        if (UserInfo.isLogin(getContext()))
            componentRelativeInvoker.getContentComponent(item,componentId, article_id, UserInfo.getUserInfo(getContext()).getUserid(), vid, 0, 0, 1, new LiveProgramListReciver());
        else
            componentRelativeInvoker.getContentComponent(item,componentId, article_id, null, vid, 0, 0, 1, new LiveProgramListReciver());
    }

    /**
     * 设置日期列表
     *
     * @param programListItems
     */
    public void setDatePrograms(List<LiveProgramListReciver.ProgramWeekItem> programListItems) {
        navigateItems.clear();
        String nowDate = getNowDate();
        for (int i = 0; i < programListItems.size(); i++) {
            SimpleNavigateItem catalogItem = new SimpleNavigateItem();
            catalogItem.index = i;
            if (programListItems.get(i).getDate().equals(nowDate)) {
                todayPosition = i;
                catalogItem.name = getResources().getString(R.string.today);
            } else {
                catalogItem.name = programListItems.get(i).getTitle();
            }
            navigateItems.add(catalogItem);
        }
    }


    protected String getNowDate() {
        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
        String dateString = formatter.format(currentTime);
        return dateString;
    }

    public void scrollToPosition() {
        mCatalogItemContainer.postDelayed(() -> {
            if (scrollToPosition) {
                scrollToPosition = false;
                LiveProgramItemFragment f = ((LiveProgramItemFragment) contentFragmentAdapter.getList().get(playFragmentPosition));
                f.programList.smoothScrollToPosition(f.liveProgramAdaptor.selectedIndex);
            }
        }, 400);

    }

    protected int playFragmentPosition;
    protected boolean scrollToPosition = false;
    public boolean isFirstPlay = true;

    public void setPlay() {
        if (!isFirstPlay)
            return;
        isFirstPlay = false;
        if (contentFragmentAdapter != null) {
            List<Fragment> fragments = contentFragmentAdapter.getList();
            for (int k = 0; k < fragments.size(); k++) {
                LiveProgramItemFragment liveFragment = (LiveProgramItemFragment) fragments.get(k);
                if (liveFragment.liveProgramAdaptor.livingIndex != -1) {
                    liveFragment.liveProgramAdaptor.selectedIndex = liveFragment.liveProgramAdaptor.livingIndex;
                    liveFragment.liveProgramAdaptor.livingIndex = -1;
                    liveFragment.liveProgramAdaptor.notifyDataSetChanged();
                    if (getActivity() instanceof VideoLiveDetailActivity) {
                        ProgramListItem item = liveFragment.liveProgramAdaptor.getItem(liveFragment.liveProgramAdaptor.selectedIndex);
                        ((VideoLiveDetailActivity) getActivity()).freshShiled(item);
                    }
                }else{
                    //这里是为了解决62612 【APP工厂】对智能媒资直播的节目单，进入屏蔽时的详情，在加载节目单时，点击播放，显示的是直播内容，不是屏蔽的图片
                   new Handler().postDelayed(new Runnable() {
                       @Override
                       public void run() {
                           if (liveFragment.liveProgramAdaptor.livingIndex != -1){
                               if (getActivity() instanceof VideoLiveDetailActivity) {
                                   liveFragment.liveProgramAdaptor.selectedIndex = liveFragment.liveProgramAdaptor.livingIndex;
                                   liveFragment.liveProgramAdaptor.livingIndex = -1;
                                   liveFragment.liveProgramAdaptor.notifyDataSetChanged();
                                   ProgramListItem item = liveFragment.liveProgramAdaptor.getItem(liveFragment.liveProgramAdaptor.selectedIndex);
                                   ((VideoLiveDetailActivity) getActivity()).freshShiled(item);
                               }
                           }
                       }
                   },2000);
                }

            }
        }
    }

    public void freshAdapter(ProgramListItem item) {
        if (contentFragmentAdapter != null) {
            List<Fragment> fragments = contentFragmentAdapter.getList();
            LiveProgramItemFragment liveFragment = (LiveProgramItemFragment) fragments.get(playFragmentPosition);
            for (int i = 0; i < liveFragment.liveProgramAdaptor.getCount(); i++) {
                if (item.getId() == liveFragment.liveProgramAdaptor.getItem(i).getId()) {
                    liveFragment.liveProgramAdaptor.selectedIndex = i;
                }
            }
            liveFragment.liveProgramAdaptor.notifyDataSetChanged();
        }
        scrollToPosition();
    }

    public ProgramListItem setPlayingStartTime(long time) {
        ProgramListItem itenrn = null;
        List<Fragment> fragments = contentFragmentAdapter.getList();
        int tempPosition = -1;
        for (int k = 0; k < fragments.size(); k++) {
            LiveProgramItemFragment liveFragment = (LiveProgramItemFragment) fragments.get(k);
            List<ProgramListItem> items = liveFragment.liveProgramAdaptor.getListContentData();
            if (items != null) {
                for (int i = 0; i < items.size(); i++) {
                    ProgramListItem item = items.get(i);
                    if (time == -1) {//回到直播
                       if (ProgramListItem.getItemState(item).equals(ProgramListItem.GuideItemState.LIVE)){
                           playFragmentPosition = k;
                           tempPosition = i;
                           itenrn = item;
                           break;
                       }
                    }else{//回看
                        if (item.getStartLong() < time) {
                            playFragmentPosition = k;
                            tempPosition = i;
                            itenrn = item;
                        } else {
                            break;
                        }
                    }

                }
            }

        }
        for (int k = 0; k < fragments.size(); k++) {
            LiveProgramItemFragment liveFragment = (LiveProgramItemFragment) fragments.get(k);
            liveFragment.liveProgramAdaptor.selectedIndex = -1;
        }

        ((LiveProgramItemFragment) fragments.get(playFragmentPosition)).liveProgramAdaptor.selectedIndex = tempPosition;
        mCatalogItemContainer.setCurrentTab(playFragmentPosition);
        scrollToPosition = true;
        return itenrn;
    }

    /**
     * 节目单获取失败或者没有数据
     */
    public void setDefaultProgramsList() {
        navigateItems.clear();
        todayPosition = (13 - 1) / 2;
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat(getActivity().getString(R.string.program_date_formate));
        for (int i = 0; i < 13; i++) {
            long timeStamp = date.getTime() - (24 * 60 * 60 * 1000) * (todayPosition - i);
            SimpleNavigateItem catalogItem = new SimpleNavigateItem();
            catalogItem.index = i;
            if (i == todayPosition) {
                catalogItem.name = getResources().getString(R.string.today);
            } else {
                catalogItem.name = sdf.format(new Date(timeStamp));
            }
            navigateItems.add(catalogItem);
        }
    }

    public void choooseMiddle() {
       /* RadioButtonX radioButtonX = (RadioButtonX) mCatalogGroupContainer.getChildAt(todayPosition);
        radioButtonX.setChecked(true);*/
        mCatalogItemContainer.setCurrentTab(todayPosition);
        playFragmentPosition = todayPosition;
    }

    @Override
    public void success(LiveProgramListReciver result) {
        if (getActivity()==null||requireActivity().isFinishing()||requireActivity().isDestroyed()){
            return;
        }
        if (result.state && result.programListItems != null) {
            if (result.programListItems.size() > 0) {
                setDatePrograms(result.programListItems);
                final ArrayList<Fragment> list = new ArrayList<Fragment>();

                for (int i = 0; navigateItems != null && i < navigateItems.size(); i++) {
                    //加按钮对应的fragment
                    Fragment fragment = getViewContentFragment(navigateItems.get(i));
                    if (fragment != null) {
                        list.add(fragment);
                    }
                }
                try {
                    if (list.size() > 0) {
                        //如果子项只有一个table  那就把上面的tableNavigate隐藏掉
                        setCatalogItemContentList(getChildFragmentManager(), list);
                        List<IAdapterTitle> titleList = new ArrayList<>();
                        titleList.addAll(navigateItems);
                        contentFragmentAdapter.titleList = titleList;
                        //  AppThemeTabLayoutStyle.setLiveTabLayoutStyle(getActivity(),mCatalogItemContainer, TabLayout.MODE_SCROLLABLE);
                        mCatalogItemContainer.setViewPager(mContentViewPager);
                    }
                } catch (Exception e) {
                    if (e != null) {
                        e.printStackTrace();
                        Log.e(TAG, e.getMessage() + "");
                    }
                }
                choooseMiddle();
                int index = 0;
                for (LiveProgramListReciver.ProgramWeekItem programList : result.programListItems) {
                    LiveProgramItemFragment fragment = (LiveProgramItemFragment) contentFragmentAdapter.getItem(index);
                    if (fragment == null)
                        continue;
                    for (int i = 0; i < programList.programList.size(); i++) {
                        ProgramListItem item = programList.programList.get(i);
                        if (AppointmentManager.INSTANCE.isAppointment(article_id,item.getId()+"")) {
                            item.setAppointment(true);
                          //  item.setAppointmentId(appointmentMap.get(item.getId()));
                        } else {
                            item.setAppointment(false);
                        }
                    }
                    fragment.setArticleIdAndName(article_id + "", channelName);
                    fragment.setListData(programList.programList);
                    String key = navigateItems.get(index).name;
                    index++;
                    LinkedHashMap<String, List<ProgramListItem>> map = new LinkedHashMap<>();
                    map.put(key, programList.programList);
                    allProgramList.add(map);
                }
                List<ProgramListItem> allProgram = new ArrayList<>();
                for (LiveProgramListReciver.ProgramWeekItem programList : result.programListItems) {
                    allProgram.addAll(programList.programList);
                }
                if (getActivity() instanceof VideoLiveDetailActivity) {
                    ((VideoLiveDetailActivity) getActivity()).setPrograms(allProgram);
                }
                mRootView.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        lastSelectIndex = todayPosition;
                        mCatalogItemContainer.setCurrentTab(todayPosition);
                    }
                }, 1000);
                if (programGetHandle != null)
                    programGetHandle.getProgram(allProgramList);
                else
                    allProgramList.clear();
            }
        } else {
            fault(null);
        }
    }

    @Override
    public void fault(Object data) {
        if (getActivity()==null||requireActivity().isFinishing()||requireActivity().isDestroyed()){
            return;
        }
        setDefaultProgramsList();
        super.setTabLayoutData();
      /*  RadioButtonX radioButtonX = (RadioButtonX) mCatalogGroupContainer.getChildAt(todayPosition);
        radioButtonX.setChecked(true);*/
        mCatalogItemContainer.setCurrentTab(todayPosition);
        for (int index = 0; index < contentFragmentAdapter.getCount(); index++) {
            LiveProgramItemFragment fragment = (LiveProgramItemFragment) contentFragmentAdapter.getItem(index);
            fragment.setListData(null);
        }
        mRootView.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (getActivity()==null||requireActivity().isFinishing()||requireActivity().isDestroyed()){
                    return;
                }
                lastSelectIndex = todayPosition;
                mCatalogItemContainer.setCurrentTab(todayPosition);
//                scroll2ChoosedIndex();
            }
        }, 1000);
    }

    public interface GetProgramData {
        void getProgram(List<Map<String, List<ProgramListItem>>> data);
    }

    @Override
    protected void setCatalogItemContentList(FragmentManager manager, ArrayList<Fragment> list) {
        super.setCatalogItemContentList(manager, list);
        mContentViewPager.setOffscreenPageLimit(list.size());
    }

    @Override
    public Fragment getViewContentFragment(SimpleNavigateItem catalogItem) {
        LiveProgramItemFragment fragment = new LiveProgramItemFragment();
        fragment.liveTableIndex = catalogItem.index;
        Bundle bundle = new Bundle();
        bundle.putParcelable("data", catalogItem);
        if (programListItems != null && programListItems.size() == navigateItems.size()) {
            List<ProgramListItem> programList = programListItems.get(catalogItem.index).programList;
            if (programList == null)
                programList = new ArrayList<>();
            bundle.putSerializable(Program, (Serializable) programList);
        }
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        AppfacBuyEnableUtils.refresh(getActivity(), !needPay);
    }

    @Override
    public int getLayoutResID() {
        return R.layout.aappfactory_livedetail_fragment;
    }

    /*protected RadioButtonX createRadioButtonItem(SimpleNavigateItem catalogItem) {
        final RadioButtonX radioButtonX = super.createRadioButtonItem(catalogItem);
        radioButtonX.setText(catalogItem.name);
        int textColor = getResources().getColor(R.color.light_black_color);
        radioButtonX.setTextColor(textColor);
        radioButtonX.uncheckedTextColor = textColor;
        int color = Color.parseColor(AppFactoryGlobalConfig.getAppServerConfigInfo(getActivity()).getColor());
        radioButtonX.checkedTextColor = color;
        radioButtonX.drawableType = RadioButtonX.bottom;
        radioButtonX.setTextSize(12);
        radioButtonX.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
            @Override
            public boolean onPreDraw() {
                radioButtonX.getViewTreeObserver().removeOnPreDrawListener(this);
                BitmapDrawable checkedDrawableDefault = (BitmapDrawable) getResources().getDrawable(R.drawable.msgcenter_checkdrawable);
                Bitmap bitmap;
                try {
                    bitmap = BitmapUtil.zoomBitmap(checkedDrawableDefault.getBitmap(), radioButtonX.getMeasuredWidth(), checkedDrawableDefault.getBitmap().getHeight());
                } catch (Exception e) {
                    bitmap = checkedDrawableDefault.getBitmap();
                    e.printStackTrace();
                }
                BitmapDrawable checkedDrawable = new BitmapDrawable(getResources(), bitmap);
                BitmapDrawable uncheckedDrawable = new BitmapDrawable(getResources(), bitmap);
                radioButtonX.checkedDrawable = checkedDrawable;
                radioButtonX.uncheckedDrawable = uncheckedDrawable;
                radioButtonX.updateEffDrawable();
                radioButtonX.setTint(AppFactoryGlobalConfig.getAppServerConfigInfo(getActivity()).getMainColor(), Color.TRANSPARENT);
                return true;
            }
        });
        return radioButtonX;
    }*/

  /*  @Override
    protected TableCatalogItemsFragmentBase<SimpleNavigateItem>.RadioButtonCheckeChangedListener getRadioButtonCheckeChangedListener(
            RadioButtonX radioButtonX, int index) {
        return new RadioButtonCheckeChangedListenerX(radioButtonX, index);
    }


    private class RadioButtonCheckeChangedListenerX extends RadioButtonCheckeChangedListener {

        public RadioButtonCheckeChangedListenerX(RadioButtonX radioButtonX,
                                                 int index) {
            super(radioButtonX, index);
        }

        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            super.onCheckedChanged(buttonView, isChecked);
            if (isChecked) {
                radioButtonX.getPaint().setFakeBoldText(true);
            } else {
                radioButtonX.getPaint().setFakeBoldText(false);
            }
        }
    }*/

    /*protected void invalidateRadioButtonsPadding() {
        int margin = getResources().getDimensionPixelSize(R.dimen.appfactory_liveprogramtable_btnmargin);
        int containerWidth = topContainer.getMeasuredWidth();
        int scrollerWidth = mCatalogItemContainer.getMeasuredWidth();
        int gap = containerWidth - scrollerWidth;
        if (gap < 0)
            gap = 0;
//        mCatalogGroupContainer.invalidatePadding2(margin, gap, true);
    }
*/

    public void selectLiveTableChild(int tableIndex, int childIndex) {
        if (contentFragmentAdapter == null || contentFragmentAdapter.getCount() == 0 || tableIndex >= contentFragmentAdapter.getCount())
            return;
        for (int i = 0; i < contentFragmentAdapter.getCount(); i++) {
            LiveProgramItemFragment fragment = (LiveProgramItemFragment) contentFragmentAdapter.getItem(i);
            if (tableIndex == i)
                fragment.liveProgramAdaptor.selectedIndex = childIndex;
            else
                fragment.liveProgramAdaptor.selectedIndex = -1;
            fragment.updateChoosePlayIndex(tableIndex);
        }
    }
    @Override
    public void onSaveInstanceState(Bundle outState) {
        outState.putString("componentId", componentId);
        outState.putString("article_id", article_id);
        outState.putString("vid", vid);
        super.onSaveInstanceState(outState);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (componentRelativeInvoker != null)
            componentRelativeInvoker.destory();
    }

//    HashMap<Integer, Integer> appointmentMap = new HashMap<>();//key:节目单id,value:预约id
//
//    private void getAppointmentList(String contentID) {
//        appointmentMap.clear();
//        DataInvokeUtil.getZiMeiTiApi()
//                .getAppointmentList(UserInfo.getUserInfo(getContext()).getUserid(), 1, contentID, 1, 200)
//                .subscribeOn(Schedulers.io())
//                .observeOn(AndroidSchedulers.mainThread())
//                .subscribe(new Observer<JSONObject>() {
//                    @Override
//                    public void onSubscribe(@NonNull Disposable d) {
//
//                    }
//
//                    @Override
//                    public void onNext(@NonNull JSONObject jsonObject) {
//                        if (getActivity()==null||requireActivity().isFinishing()||requireActivity().isDestroyed()){
//                            return;
//                        }
//                        try {
//                            if (jsonObject.optBoolean("state")) {
//                                JSONObject data = jsonObject.optJSONObject("data");
//                                if (data != null) {
//                                    JSONArray meta = data.optJSONArray("meta");
//                                    if (meta != null && meta.length() > 0) {
//                                        for (int i = 0; i < meta.length(); i++) {
//                                            int playBillid = meta.getJSONObject(i).optInt("playbill_id");//节目单id
//                                            int id = meta.getJSONObject(i).optInt("id");//预约id
//                                            appointmentMap.put(playBillid, id);
//                                        }
//                                    }
//                                }
//                            }
//                        } catch (JSONException e) {
//                            e.printStackTrace();
//                        }
//                    }
//
//                    @Override
//                    public void onError(@NonNull Throwable e) {
//
//                    }
//
//                    @Override
//                    public void onComplete() {
//
//                    }
//                });
//
//    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void loginState(LoginEvent loginEvent) {
        if (getActivity()==null||requireActivity().isFinishing()||requireActivity().isDestroyed()){
            return;
        }
        if (UserInfo.isLogin(getContext())) {//用户登录，请求预约节目单
            //getAppointmentList(article_id);
            getRelateNewsList();
        }
    }
}